package com.auto.autoapp.task

import com.auto.autoapp.AutoApplication
import com.auto.autoapp.constants.Dy
import com.auto.autoapp.constants.SearchPageId
import com.auto.autoapp.model.AccountRaiseSetting
import com.auto.autoapp.step.changeSearchResultTab
import com.auto.autoapp.step.clickCommentBtn
import com.auto.autoapp.step.clickLike
import com.auto.autoapp.step.exchangeVideo
import com.auto.autoapp.step.getDyCode
import com.auto.autoapp.step.getVideoDetail
import com.auto.autoapp.step.sendComment
import com.auto.autoapp.step.toDyIndex
import com.auto.autoapp.ui.result.ResultActivity
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.util.addLog
import com.auto.autoapp.util.clickOrTap
import com.auto.autoapp.util.getNodeById
import com.auto.autoapp.util.getNodeList
import com.ven.assists.AssistsCore
import com.ven.assists.AssistsCore.des
import com.ven.assists.AssistsCore.setNodeText
import com.ven.assists.stepper.Step
import com.ven.assists.stepper.StepCollector
import com.ven.assists.stepper.StepImpl
import kotlinx.coroutines.delay
import kotlin.random.Random

/**
 * 养号
 * 活跃账号，执行浏览视频，关注作者，点赞视频等
 * 1. 获取当前抖音号
 * 2. 搜索关键字（来自本地配置 AccountRaiseSetting.keyword）
 * 3. 浏览视频（AccountRaiseSetting.browseDurationSeconds）
 * 4. 点赞（AccountRaiseSetting.likeProbability）
 * 5. 评论（AccountRaiseSetting.commentProbability，评论文字列表）
 * 6. 滑屏进入下一个视频
 * 7. 循环执行 3--6
 */
class AccountRaiseTask : StepImpl() {

    override fun onImpl(collector: StepCollector) {
        // 读取本地配置
        var setting = SpUtil.getAccountRaiseSetting()
        var collectedCount = 0

        collector
            // Step 1: 前往首页并获取当前抖音号
            .next(1) {
                setting = SpUtil.getAccountRaiseSetting()
                collectedCount = 0
                return@next toDyIndex(nextStep = 2)
            }
            .next(2) {
                addLog("跳转首页成功，开始切换tab->我的")

                val result = Dy.ID_TAB_MINE.clickOrTap()
                if (result.isFailure) {
                    addLog("切换至我的页面失败")
                    return@next Step.repeat
                }
                delay(1500)
                val codeResult = getDyCode()
                if (codeResult.isFailure) {
                    addLog("未获取到抖音号，请确认是否已登录")
                    return@next Step.none
                }
                delay(500)
                val indexTab = Dy.ID_TAB_MINE.getNodeById(last = false)
                if (indexTab.isFailure) {
                    addLog("无法切换至首页，请检查页面")
                    return@next Step.none
                }

                val toIndexResult = indexTab.getOrNull()!!.clickOrTap()
                if (toIndexResult.isSuccess) {
                    addLog("切换至首页成功")
                } else {
                    addLog("切换至首页失败")
                }
                return@next Step.get(3)

            }
            // Step 2: 搜索关键字
            .next(3) {
                val searchNodeResult = Dy.ID_INDEX_SEARCH_NODE.clickOrTap()
                if (searchNodeResult.isFailure) {
                    addLog("未找到搜索入口，请重试")
                    AssistsCore.back()
                    delay(1000)
                    return@next Step.repeat
                }
                addLog("进入搜索，关键词：${setting.keyword}")
                delay(2000)
                val editText = AssistsCore.findById(Dy.ID_SEARCH_INPUT).firstOrNull()
                if (editText != null) {
                    editText.setNodeText(setting.keyword)
                    delay(1000)
                    Dy.SEARCH_BTN.clickOrTap()
                    addLog("已执行搜索")
                    delay(1500)
                    val changeTabResult = changeSearchResultTab("视频")
                    if (changeTabResult.isSuccess) {
                        delay(3000)
                        val videoListResult = SearchPageId.TAB_CONTENT_RV.getNodeById()
                        if (videoListResult.isFailure) {
                            addLog("未找到视频列表")
                            return@next Step.none
                        }
                        delay(1000)
                        val videoList = videoListResult.getOrNull()!!
                        val childCount = videoList.childCount
                        addLog("视频列表数量：$childCount")
                        val clickResult = videoList.getChild(0).clickOrTap()
                        if (clickResult.isSuccess) {
                            addLog("点击视频，开始浏览")
                            return@next Step.get(4)
                        } else {
                            addLog("点击视频失败")
                            return@next Step.none
                        }
                    }
                    return@next Step.none

                } else {
                    addLog("搜索输入框未找到")
                    return@next Step.none
                }
            }
            // Step 3: 浏览视频（时长）
            .next(4) {
                val seconds = setting.browseDurationSeconds.coerceAtLeast(1)
                addLog("开始浏览视频：${seconds}s")
                delay(seconds * 1000L)
                return@next Step.get(5)
            }
            // Step 4: 点赞（概率）评论（概率）
            .next(5) {
                var needAdd = false


                //是否已经点过赞
                val hasLiked =
                    Dy.ID_VIDEO_LIKE.getNodeList().getOrNull()?.firstOrNull()?.des()
                        ?.contains("已") == true
                val roll = Random.nextInt(0, 100)
                if (hasLiked) {
                    addLog("已经点过赞，跳过点赞逻辑")
                } else {
                    val likeProb = setting.likeProbability.coerceIn(0, 100)

                    val needLike = roll < likeProb
                    addLog("点赞概率：${likeProb}%,当前点数：$roll,是否执行点赞：${if (needLike) "执行" else "不执行"}")
                    if (needLike) {
                        val likeResult = clickLike()
                        if (likeResult.isSuccess) {
                            needAdd = true
                            delay(1000)
                        } else {
                            addLog("点赞失败")
                        }
                    } else {
                        addLog("点赞跳过")
                    }
                }

                val commentProb = setting.commentProbability.coerceIn(0, 100)
                val commentRoll = Random.nextInt(0, 100)
                val needComment = roll < commentProb
                addLog("评论概率：${commentProb}%,当前点数：$commentRoll,是否执行评论：${if (needComment) "" else "不"}执行")
                val comments = setting.commentContentList
                if (roll < commentProb) {
                    val commentResult = sendComment(comments.toMutableList())
                    if (commentResult.isSuccess) {
                        needAdd = true
                        delay(1000)

                    }
                }

                if (needAdd) {
                    collectedCount++
                }

                addLog("需要收集：${setting.collectCount}次，已收集：${collectedCount}次")

                if (collectedCount >= setting.collectCount) {
                    addLog("收集完毕，流程结束，共计${collectedCount}次")
                    return@next Step.none
                }

                return@next Step.get(6)
            }
            // Step 6: 滑屏进入下一个视频，并循环 4--6
            .next(6) {
                val exch = exchangeVideo()
                if (exch.isFailure) {
                    addLog("滑屏进入下一个视频失败")
                    return@next Step.none
                }
                // 可选：查看视频信息以便后续判断
//                getVideoDetail()
                delay(800)
                // 循环执行 4--6（即继续浏览->点赞->评论->滑屏）
                return@next Step.get(4)
            }
    }
}